//
//  String+Url.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/4/14.
//

import Foundation

struct ParsedURL {
    let scheme: String?
    let host: String?
    let port: Int?
    let path: String
    let queryItems: [String: String]
    let fragment: String?
}

extension String {
    var parsedURL: ParsedURL? {
        guard let url = URL(string: self),
              let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
            return nil
        }
        
        let queryDict = Dictionary(uniqueKeysWithValues: (components.queryItems ?? []).map {
            ($0.name, $0.value ?? "")
        })
        
        return ParsedURL(
            scheme: components.scheme,
            host: components.host,
            port: components.port,
            path: components.path,
            queryItems: queryDict,
            fragment: components.fragment
        )
    }
    
    var isURL: Bool {
        if let url = URL(string: self) {
                return url.scheme == "http" || url.scheme == "https"
            }
            return false
    }

}

